import {Injectable} from '@angular/core';
import {Http, Headers, Request, RequestOptions, Response, RequestMethod, URLSearchParams} from '@angular/http';
import {Observable} from 'rxjs/Observable';
import {Subject} from 'rxjs/Subject';

import {User} from '../model/user-model';

@Injectable()
export class UserRegisterService {
  public userRegisterURL = "http://localhost:3000/signup";
  public testEmailURL = "";
  public subject: Subject<User> = new Subject<User>();

  constructor(public http: Http) {
  }

  public get currentUser(): Observable<User> {
    return this.subject.asObservable();
  }

  public register(user: User) {

    return this.http
      .post(this.userRegisterURL,user)
      .map((response: Response) => {
        let user = response.json();
        if(!user.error){
          localStorage.setItem("currentUser", JSON.stringify(user));
          this.subject.next(user);
        }
        return user;
      });
  }

  public testEmail(email: string) {
    return this.http.get(this.testEmailURL)
      .map((response: Response) => response.json());
  }
}
